
var Global = {};
Global["tree"] = null;//树菜单
Global["tree_node_data"] = null;//当前树节点
Global["data_type"] = 0;//数据来源 1:菜单  2:搜索
let safe_name = "隐藏目录";
layui.use('laydate', function () {
  initTree();
  func_slt_btn();//搜索

  initView();
  func_miehua();
  setTimeout(function(){
    $("#memu").trigger("click");
  },400);
});
function func_miehua() {
  $("#check_all").click(() => {
    $(".nas_check").prop("checked", true);
  });
  var mas = 0;
  $("#meihua").click(function () {


    if (mas == 0) {
      $('#main').masonry({
        isAnimated: true,
        itemSelector: '.item', // 选择子项的 CSS 选择器
        columnWidth: 210, // 设置列宽
        gutter: 10 // 设置列与列之间的间距
      });
      mas = 1;
    } else {
      $grid = $("#main");
      $grid.masonry('reloadItems').masonry('layout');

    }


    layer.closeAll();
  });
}
function initFileExt() {//初始化扩展名
  myData["getNasFileExt"]((response) => {

    $("#nas_file_ext").html("");
    $("#slt_nas_file_ext").html("");
    var html = "";
    response.forEach(item => {
      html += `<option value="${item}">${item}</option>`;
    });
    $("#slt_nas_file_ext").html(`<option value="">全部</option>${html}`);
    $("#nas_file_ext").html(html);

  });
}
function initView() {//菜单缩放
  layui.laydate.render({
    elem: '#slt_nas_create_date'

    , range: '~'
    , format: 'yyyy-MM-dd'
  });
  $("#spread").click(function () {

    var spread = $(this).attr("data-spread");

    if (spread == 0) {
      $(this).attr("data-spread", 1);
      $(this).addClass("layui-icon-shrink-right");
      $(this).removeClass("layui-icon-spread-left");
      $(".layui-side-scroll").css("width", "500px");
      $("#leftMenu").css("width", "500px");

    } else {
      $(this).attr("data-spread", 0);
      $(this).removeClass("layui-icon-shrink-right");
      $(this).addClass("layui-icon-spread-left");
      $(".layui-side-scroll").css("width", "");
      $("#leftMenu").css("width", "");
    }
  });
}
function func_slt_btn() {

  $("#slt_btn").on("click", function () {
    if ($(this).hasClass("layui-btn-disabled")) {

      return;
    }
    var param = {};
    param["abs_folder_path"] = $("#slt_abs_folder_path").val();
    param["nas_search_key"] = $("#slt_nas_search_key").val();
    param["nas_file_ext"] = $("#slt_nas_file_ext").val();
    param["nas_create_date"] = $("#slt_nas_create_date").val();

    if ($("#slt_nas_create_date").val() != "") {
      param["nas_create_date_begin"] = $("#slt_nas_create_date").val().split("~")[0].trim();
      param["nas_create_date_end"] = $("#slt_nas_create_date").val().split("~")[1].trim();
    }
    // if (param["nas_search_key"] == "") {
    //   layer.msg("请输入搜索关键词");
    //   return;
    // }
    let safe = myData["getSession"]("safeFolderPwd");
    if (safe == null) {
      param["safe"] = safe_name;
    } else {
      param["safe"] = "";
    }


    //******************************** */
    $grid = $("#main");
    $grid.html("");
    $grid.css("height", "auto");
    var flow = layui.flow;
    // 流加载实例
    flow.load({
      elem: '#main', // 流加载容器
      scrollElem: '#flowBody',
      moreText : "<hr>",
      isAuto:true,
      done: function (page, next) { // 加载下一页
        
       
        param["offset"] = page-1;
        myData["getSltKeySearch"](param, (response) => {
          Global["data_type"] = 2;
          
          markMain(response);
          cloading();
          var lis = [];
          if(response["files"].length>=25){
            next(lis.join(''), page < page+1);
          }else{
            next(lis.join(''), page < page);
          }
        });
      }
    });
    //******************************** */
  });
}
function safeFolder(abs_path, callback) {
  let idx = abs_path.indexOf(safe_name);
  let safe = myData["getSession"]("safeFolderPwd");

  if (idx != -1 && safe == null) {
    layer.confirm(`<input type="password" name="password" required="" lay-verify="required" lay-vertype="tips" 
    value="741852" placeholder="请输入密码" autocomplete="off" class="layui-input">`, {
      btnAsync: true,
      title: "请输入密码：",
      btn: ['确定', '关闭'] // 按钮
    },
      function (index, layero, that) {
        let pwd = $("input", $(layero)).val();
        myData["safeFolderPwd"](pwd, callback);
      });
  } else {
    callback();
  }

}
function initTree() {
  var tree = layui.tree;
  Global["tree"] = tree.render({
    elem: '#ID-tree-demo-showCheckbox',
    data: [],
    onlyIconControl: true,
    id: 'test',
    click: function (obj) {
      let abs_path = obj.data.abs_path;
      safeFolder(abs_path, function () {
        $("#slt_abs_folder_path").val(abs_path);
        Global["tree_node_data"] = obj.data;
        tree2Body();
      });
    }
  });
}
function tree2Body() {//从树节点创建主数据
  loading("<a class='loadLayer'></a>正在加载");
  asyncFlag = false;
  asyncDelayedLoop(() => {
    myData["getLoadFileName"]((response) => {

      $(".loadLayer").html(`【${response}】`);
    });
  });
  let p = Global["tree_node_data"]["abs_path"];

  //******************************** */
  $grid = $("#main");
  $grid.html("");
  $grid.css("height", "auto");
  var flow = layui.flow;
  // 流加载实例
  flow.load({
    elem: '#main', // 流加载容器
    scrollElem: '#flowBody',
    end: "<hr>",
    done: function (page, next) { // 加载下一页
      
      // 模拟插入
      myData["getFile"](p, (response) => {
        Global["data_type"] = 1
        markMain(response);
        cloading();
        asyncFlag = true;
        var lis = [];
        next(lis.join(''), page < 1);
      });

    }
  });
  //******************************** */


}
function markMain(response) {
  let items = response["files"];

  Global["root"] = response["root_dir"];
  $grid = $("#main");
  // $grid.html("");
  items.forEach((item) => {
    var elem = $(myView["getElement"](item));
    elem.data("item", item);
    $grid.append(elem);
  });
  $("img", ".item").click(function () {
    data = $(this).parents(".item").data("item");
    openItem(data);
  });

  setTimeout(function () {
    $("#meihua").trigger("click");
  }, 500);



}
function getPath(path) {
  return Global["root"] + path;
}
function getNasInfosBySame(nas_abs_file_path) {
  myData["getNasInfosBySame"](nas_abs_file_path, function (response) {
    $("#win_nas_abs_file_path").html("");
    response.forEach(my_item => {
      my_nas_abs_file_path = getPath(my_item["nas_abs_file_path"]);
      var my_del = `<button class="layui-btn layui-btn-xs my_del layui-btn-danger">删除</button>`;
      if (nas_abs_file_path == my_nas_abs_file_path) {
        my_del = "";
      }
      elem = `<div style="clear:both;" class="my_same_item">
      <div style="float:left;" class="my_same_item_path">${my_nas_abs_file_path}</div>
      <div style="float:right;">
        ${my_del}
        <button class="layui-btn layui-btn-xs my_wz">位置</button>
      </div>
      <hr>
      </div>`;
      var my_div = $(elem);

      my_div.data("item", my_item);
      $("#win_nas_abs_file_path").append(my_div);

    });
    $(".my_del").off("click");
    $(".my_del").on("click", function () {
      var temp220 = $(this).parents(".my_same_item").data("item");

      temp220_nas_abs_file_path = getPath(temp220["nas_abs_file_path"]);
      temp220_nas_abs_file_raw_path = getPath(temp220["nas_abs_file_raw_path"]);
      if (window.confirm('你确定要删除吗？')) {
        setTimeout(() => {
          myData["delFile"](temp220_nas_abs_file_path, temp220_nas_abs_file_raw_path, (response) => {
            getNasInfosBySame(nas_abs_file_path);
            refBody();
          });
        }, 400);


      };
    });
    $(".my_wz").off("click");
    $(".my_wz").on("click", function () {
      var temp220 = $(this).parents(".my_same_item").data("item");
      var temp220_nas_abs_file_path = getPath(temp220["nas_abs_file_path"]);
      myData["openFileFromExplorer"](temp220_nas_abs_file_path);

    });
    $(".my_same_item_path").off("dblclick");
    $(".my_same_item_path").on("dblclick ", function () {
      var html = $(this).html();
      copyTextToClipboard(html);
    });
  });
}
function openItem(param) {
  let nas_file_type = param["nas_file_type"];
  let nas_file_ext = param["nas_file_ext"];

  let nas_abs_file_path = getPath(param["nas_abs_file_path"]);
  let nas_abs_folder_path = getPath(param["nas_abs_folder_path"]);
  let nas_abs_file_raw_path = getPath(param["nas_abs_file_raw_path"]);
  let nas_search_key = param["nas_search_key"];
  $("#nas_file_ext").val(nas_file_ext);

  if (nas_search_key != null) {
    $("#nas_search_key").val(nas_search_key);
  }
  //相同文件
  getNasInfosBySame(nas_abs_file_path);



  if (nas_file_type == "图片") {
    $("#win_main").html(`<img src="${nas_abs_file_path}" width="100%">`);
  } else if (nas_file_type == "视频") {
    var html = `
    <video style="max-width:30vw"   controls="controls" >
    <source src="${nas_abs_file_path}" type="video/mp4" />
    <source src="movie.ogg" type="video/ogg" />
    <source src="movie.webm" type="video/webm" />
    </video>
    `;
    $("#win_main").html(html);
  } else if (nas_file_type == "音频") {
    var html = `
    <video style="max-width:30vw"  controls="controls"  >
    <source src="${nas_abs_file_path}" type="video/mp4" />
    <source src="movie.ogg" type="video/ogg" />
    <source src="movie.webm" type="video/webm" />
    </video>
    `;
    $("#win_main").html(html);
  } else {
    $("#win_main").html(`<img src="${nas_abs_file_raw_path}"  width="50%">`);
  }

  layer.open({
    type: 1,
    area: ['80%', '80%'],
    shade:false,
    content: $('#formTemp'),
    btn: ['提交', "批量提交", "文件位置", "删除", '关闭'],
    end: () => {
      $("#win_main").html("");
      $('#formTemp').hide();
    },
    btn4: () => {//删除

      if (window.confirm('你确定要删除吗？')) {
        try {
          var video = $("video ", "#win_main")[0];
          video.pause(); // 确保视频停止播放
          video.remove(); // 移除视频元素
        } catch (err) {
        }
        setTimeout(() => {
          myData["delFile"](nas_abs_file_path, nas_abs_file_raw_path, (response) => {
            refBody();
            layer.closeAll();
          });
        }, 400);


      };
      return false;
    },
    btn3: () => {//文件位置
      myData["openFileFromExplorer"](nas_abs_file_path);
    },
    btn2: () => {//批量提交
      var datas = [];
      loading();
      $(".nas_check:checked").each((index, element) => {
        let dataD = $($(element).attr("data-item-id")).data("item");
        let data = {
          "nas_search_key": $("#nas_search_key").val(),
          "nas_abs_file_path": getPath(dataD["nas_abs_file_path"]),
          "nas_abs_folder_path": getPath(dataD["nas_abs_folder_path"]),
          "nas_file_type": dataD["nas_file_type"],
          "nas_abs_file_raw_path": getPath(dataD["nas_abs_file_raw_path"]),
          "nas_file_md5": dataD["nas_file_md5"],
        };
        datas.push(data);
      });
      myData["addNasInfos"](datas, function (response) {
        refBody();
        cloading();
      });
      return false;
    },
    btn1: () => {//提交
      var data = {
        "nas_search_key": $("#nas_search_key").val(),
        "nas_abs_file_path": nas_abs_file_path,
        "nas_abs_folder_path": nas_abs_folder_path,
        "nas_file_type": nas_file_type,
        "nas_abs_file_raw_path": nas_abs_file_raw_path,
        "nas_file_md5": param["nas_file_md5"],
      };
      loading();
      myData["addNasInfo"](data, (response) => {

        refBody();
        cloading();
      });
    }

  });
}
function refBody() {
  if (Global["data_type"] == 1) {
    tree2Body();
  }
  if (Global["data_type"] == 2) {
    $("#slt_btn").trigger("click");
  }


}
function greet(param) {//获取树数据
  initFileExt()
  myData["getTree"](param, function (response) {
    $("#slt_btn").removeClass("layui-btn-disabled");
    var jsonObject = JSON.parse(response);
    Global["tree"].reload({
      data: jsonObject
    })
      ;
  })

}
